﻿using ClientAppraise.ViewModels.Validator;
using ClientDao.User;
using ClientInfrastructure.Util.Helper;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Win32;
using ShareCode.Dto;
using ShareCode.Dto.User.Org.Admin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Media.Imaging;

namespace ClientAppraise.ViewModels.Pages.Users.Org.Admin
{
    public partial class NewViewModel : MyObservableValidator
    {
        UserOrgDal Dal { get; }
        UserAccountDal UserAccountDal { get; }
        public NewViewModel(UserOrgDal dal, UserAccountDal userAccountDal)
        {
            this.Dal = dal;
            this.UserAccountDal = userAccountDal;

            timer = new System.Timers.Timer(1000);
            timer.Elapsed += OnTimer_Elapsed;
        }

        private readonly System.Timers.Timer timer;

        private void OnTimer_Elapsed(object? sender, ElapsedEventArgs e)
        {
            VerificationCodeTime--;

            if (VerificationCodeTime < 1)
            {
                timer.Stop();
            }
            return;
        }


        #region

        [ObservableProperty]
        [ZxRequired]
        [ServerError]
        private string? orgTitle;
        [ObservableProperty]
        [ZxRequired]
        [ServerError]
        private string? orgDomain;
        [ObservableProperty]
        private string? orgWebsite;
        [ObservableProperty]
        private string? orgLogo = "/Assets/no_picture.jpg";
        [ObservableProperty]
        private string? orgRemarks;


        [ObservableProperty]
        [ServerError]
        [ZxRequired]
        [UserName]
        private string? userName;
        [ObservableProperty]
        [ServerError]
        [UserName]
        private string? psw;
        [ObservableProperty]
        [ServerError]
        [UserName]
        private string? repsw;
        [ObservableProperty]
        private string? email;
        [ObservableProperty]
        private string? telephone;
        [ObservableProperty]
        private string? realName;
        [ObservableProperty]
        private string? birthday;
        [ObservableProperty]
        private bool gender = true;

        [ObservableProperty]
        [ZxRequired]
        [ServerError]
        [ValidatorCode]
        private string? verification;


        [ObservableProperty]
        private BitmapImage? imageVerificationCode;
        [ObservableProperty]
        private int verificationCodeTime = 60;

        #endregion

        [RelayCommand]
        public async Task OnRefreshVerificationCodeAsync()
        {
            void fun(System.IO.Stream stream)
            {

                if (!App.Current.Dispatcher.CheckAccess())
                {
                    App.Current.Dispatcher.Invoke(() => fun(stream));
                    return;
                }

                var bitmap = new BitmapImage();

                bitmap.BeginInit();
                bitmap.StreamSource = stream;
                bitmap.EndInit();

                ImageVerificationCode = bitmap;
                VerificationCodeTime = 60;
                timer.Start();
            }

            timer.Stop();

            await App.MyContentDialog.ShowRingLoadingAsync(async () =>
            {
                try
                {
                    var a = await UserAccountDal.GetVerificationCode(45, 150);
                    fun(a);
                }
                finally
                {
                    App.MyContentDialog.CloseLoading();
                }
            }, "正在获取验证码");
        }

        [RelayCommand]
        private void OnOrgSelectLogo()
        {
            var path = string.Empty;
            var openFileDialog = new OpenFileDialog()
            {
                Filter = "Files (*.JPEG)|*.JPG|*.PNG|*.GIF"//如果需要筛选txt文件（"Files (*.txt)|*.txt"）
            };

            var result = openFileDialog.ShowDialog();
            if (result!.Value)
            {
                path = openFileDialog.FileName;
            }

            OrgLogo = path;
        }

        [RelayCommand]
        private async Task OnSubmitAsync()
        {
            //App.GetRequiredService<WindowsProviderService>()?.ShowAsMain<MainWindow>();
            //var asdf = window.aaa.GetBindingExpression(TextBox.TextProperty);

            ValidateAllProperties(true);

            if (this.HasErrors)
            {
                App.MySnackbar.Danger("没有完成表单填写", "没有完成表单填写");

                return;
            }

            await App.MyContentDialog.ShowRingLoadingAsync(async () =>
            {
                try
                {
                    timer.Stop();
                    var entity = AutoMapperHelper.Map<NewOrgDto>(this) ?? new NewOrgDto();

                    ResultDto<long> reslut = await Dal.AdminNew(entity, OrgLogo);

                    if (reslut.Success)
                    {
                        App.MySnackbar.Success("成功添加企业：" + entity.OrgTitle);
                        App.MyNavigation.GoBack();
                        return;
                    }

                    //显示错误信息
                    ValidateAllPropertiesWithServer(reslut?.DetailMSg ?? []);

                    if (!string.IsNullOrEmpty(reslut?.Message))
                    {
                        App.MySnackbar.Danger("企业添加失败", reslut.Message);
                    }
                }
                catch (Exception ex)
                {
                    App.MySnackbar.Danger(ex.Message, ex.Message);
                }
                finally
                {
                    App.MyContentDialog.CloseLoading();
                }
            });

        }
    }
}
